package itdep.services.security;

import ga.domain.repository.EntityRepository;
import ga.security.SecurityConstants;
import itdep.domain.security.Account;
import itdep.services.IisEntityServiceImpl;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author Ivan Khalopik
 * @version $Revision: 39 $ $Date: 2010-06-23 10:23:37 +0000 (Wed, 23 Jun 2010) $
 */
public class AccountServiceImpl
		extends IisEntityServiceImpl<Account, AccountQuery>
		implements AccountService {

	private final PasswordEncoder passwordEncoder;

	public AccountServiceImpl(EntityRepository repository, PasswordEncoder passwordEncoder) {
		super(repository, Account.class, AccountQuery.class);
		this.passwordEncoder = passwordEncoder;
	}

	@Override
	public Account getByEmail(String email) {
		return createQuery().setEmail(email).unique();
	}

	@Override
	@Transactional
	public void refreshAccessTime(String email, Date date) {
		final Account account = getByEmail(email);
		if (account != null) {
			account.setLastLogin(date);
			update(account);
		}
	}

	@Override
	@Secured(SecurityConstants.ACL_CREATE)
	@Transactional
	public void save(Account entity) {
		entity.setPassword(passwordEncoder.encodePassword(entity.getPassword(), null));
		entity.setRegistered(new Date());
		super.save(entity);
	}
}
